﻿#include "ObjectRubberBand.h"
#include "ui_ObjectRubberBand.h"

#include "LumDebug.h"
#include <QTimer>

struct ObjectRubberBand::ObjectRubberBandData {

};

ObjectRubberBand::~ObjectRubberBand() {
    delete ui;
}

ObjectRubberBand::ObjectRubberBand(QWidget *parent) : QWidget(parent) {
    ui = new Ui::ObjectRubberBand;
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_TransparentForMouseEvents);
}

void ObjectRubberBand::changeEvent(QEvent* event) {
    QWidget::changeEvent(event);

    const auto& type = event->type();
    if(type == QEvent::ParentAboutToChange) {
        tryRubber();
    } else if(type == QEvent::ParentChange) {
        tryRubber();
    }
}

void ObjectRubberBand::tryRubber() {
    static QPointer<QTimer> timer;
    if(!timer) {
        timer = new QTimer(this);
        timer->setInterval(50);
        connect(timer.data(), SIGNAL(timeout()), this, SLOT(updateRubberGeometry()));
    }
    const auto parent_widget = parentWidget();
    if(parent_widget) {
        timer->start();
        updateRubberGeometry();
    } else {
        timer->stop();
    }
}

void ObjectRubberBand::updateRubberGeometry() {
    const auto parent_widget = parentWidget();
    if(!parent_widget) {
        return ;
    }

    auto widgetRect = parent_widget->rect();
    widgetRect.moveTopLeft(parent_widget->mapToGlobal(QPoint(0,0)));
    widgetRect.adjust(-3,-3,3,3);
    setGeometry(widgetRect);
}


